<?php

namespace app\one_api\api;

use app\common\controller\Base;
use think\Response;
use think\Db;
use think\exception\HttpResponseException;
use app\one_api\model\OneApi as apiModel;

/**
 * 框架公共控制器
 * @package app\common\controller
 */
class ApiInit extends Base
{
    public $token = '';
    protected function initialize()
    {
        parent::initialize();
        if (!isset($this->apiKey) || empty($this->apiKey) || cache('apiKey') != $this->apiKey) {
            return $this->_error('非法请求', [], 710);
        }
        // 校验授权
        $api = new \ConnectApi();
        if (!$api->initApi()) {
            exit(json_encode(['msg' => '非法请求！', 'code' => 710]));
        }

        //授权码
        $this->secret = request()->header('secret');
        // deviceId
        $this->deviceId = request()->header('Did');
        // 签名
        $this->sign = request()->header('t');
        //登录后的token
        $this->token = request()->header('token');
        //时间戳
        $this->timestamp = request()->header('timestamp');


        $params = input('body');
        if (empty($params)) {
            exit(json_encode(['msg' => '获取参数失败', 'code' => 811]));
        }
        $tmp = [];
        $params = $api->privateDecrypt($params, $this->secret, $this->deviceId, $this->timestamp);
        if (empty($params)) {
            exit(json_encode(['msg' => '获取参数失败，请通知管理员', 'code' => 810]));
        }
        parse_str($params, $_arr);
        if ($_arr) {
            foreach ($_arr as $key => $value) {
                $tmp[$key] = trim($value);
            }
        }
        $this->params = $this->_params = $tmp;

        // 验签
        if (!isset($tmp['encryptedData'])) {
            if (!$api->verifySign($this->sign, $this->params, $this->secret, $this->timestamp)) {
                $this->_error('接口验签失败', ['e' => $this->params], 910);
            }
        }
        if (!isset($this->secret)) {
            $this->_error('缺少参数: secret', [], -401);
        }
        if (!apiModel::vaildSecret($this->secret)) {
            $this->_error('非法请求', [], -401);
        }
    }

    public function _success($msg = 'success', $data = [], $code = 200, $header = [], $type = 'json')
    {
        $this->_result($msg, $data, $code, $header, $type);
    }

    public function _error($msg = 'error', $data = [], $code = 120, $header = [], $type = 'json')
    {
        $this->_result($msg, $data, $code,  $header,  $type);
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param  mixed     $data 要返回的数据
     * @param  integer   $code 返回的code
     * @param  mixed     $msg 提示信息
     * @param  string    $type 返回数据格式
     * @param  array     $header 发送的Header信息
     * @return void
     */
    public function _result($msg = '', $data = [], $code = 0, array $header = [], $type = 'json')
    {
        if ($code == 200 && !isset($data['_format'])) {
            $api = new \ConnectApi();
            $data = $api->encryptWithOpenssl($data, $this->deviceId);
        }
        $mtime = Db::name('system_config')->order('update_time DESC')->find();
        $header['config-update_time']  = $mtime['update_time'];
        $header['requestId']  = request()->header('timestamp');
        $header['X-Powered-By']  = 'Yunyingping';
        try {
            $result = [
                'code' => $code,
                'msg'  => $msg,
                'data' => mb_convert_encoding($data, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'),
            ];
        } catch (\Exception $th) {
            $result = [
                'code' => $code,
                'msg'  => $msg,
                'data' => [],
            ];
        }
        $response = Response::create($result, $type, 200, $header);
        throw new HttpResponseException($response);
    }
}
